package com.wzg.tools.pdf; /**
 * @author henryGui
 * @version V1.0
 * @Package PACKAGE_NAME
 * @Description: TODO
 * @date 2019-08-20 10:54 AM
 */


import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 功能 PDF读写类
 *
 * @CreateTime 2011-4-14 下午02:44:11
 */
public class PDFUtil {

    /**
     * 测试pdf文件的创建
     *
     * @param args
     */
    public static void main(String[] args) throws MalformedURLException {

        String content=readPdfURL(new URL("http://icid.iachina.cn/files/piluxinxi/pdf/e063e9dd-7530-4163-ae2b-848f6353917f.PDF"),1,6);
        System.out.println(content);
    }

    public static String readPdfURL(URL url,int startPage,int endPage){
        return readPdfToString("",url, startPage, endPage);

    }
    public static String readPdfFile(String fileName,int startPage,int endPage){
        return readPdfToString(fileName,null, startPage, endPage);
    }

    private static String readPdfToString(String fileName, URL url,int startPage,int endPage) {
        PDDocument document = null;

//        方式二
        try {
            if (StringUtils.isNotBlank(fileName)) {
                document = PDDocument.load(fileName);
            } else if (url != null) {
                document = PDDocument.load(url);
            }

            //int pages=document.getNumberOfPages();
            //读取文本内容
            PDFTextStripper stripper=new PDFTextStripper();
            stripper.setSortByPosition(true);
            stripper.setStartPage(startPage);
            stripper.setEndPage(endPage);
            System.out.println("--------"+stripper.getWordSeparator());
            return stripper.getText(document);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
}
